package cn.tml.innermost.user.feign;

import cn.tml.innermost.framework.entity.enums.ResultCode;
import cn.tml.innermost.framework.entity.vo.ResultMessage;
import cn.tml.innermost.framework.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.cloud.client.discovery.DiscoveryClient;

import java.util.List;

@Aspect
@Component
@Slf4j
public class UserMusicAOP {
    @Autowired
    private DiscoveryClient discoveryClient;

    @Pointcut(value = "execution(* cn.tml.innermost.user.feign.UserToMusicFeignService.*(..))")
    public void pointCut() {
    }

    @AfterReturning(pointcut="pointCut()",returning = "res")
    public void checkHTTPStatus(JoinPoint joinPoint,ResultMessage res){
        System.out.println(res.toString());
        if(res.getCode() != 200){
//            远程服务提供应用名

            String applicationName  = joinPoint.getTarget().getClass().getAnnotation(FeignClient.class).value();
            String name =joinPoint.getSignature().getName();
            String host = discoveryClient.getInstances("applicationName").get(0).getHost();
            log.error("服务调用结果异常！远程服务名称："+applicationName+"调用ip："+host+"调用方法名："+name);
            throw new ServiceException(ResultCode.API_Error);
        }

    }
}
